<%args>
	$dbh
	$auth
	$verb => 0
	$id => undef
	$filter => undef
	$filter2 => undef
	$showdel => undef
</%args>
<%init>
use Data::Dumper;
use POSIX;
#use locale;
#setlocale(&LC_COLLATE, 'ru_RU.KOI8-R');
use utf8;

#if($auth->{gid} ne '1' && $auth->{gid} ne '2') {	# только admin и manager
#	$r->status_line('');
#	$m->clear_buffer;
#	$m->abort(404);
#}

map { $_ =~ s/\D//g; } ( $verb, $id, $filter, $filter2);
map { $_ = 1 if($_ > 1) } ( $verb);
map { $_ = 0 if($_ > 1000) } ( $id);
undef $filter unless $filter;
undef $filter2 unless $filter2;
undef $showdel unless $showdel;

my %Err;
my $OK=0;

my $sth;
# Справочники

# Проезды (улицы)
my $S = $m->comp("lib.msn:listload", dbh=>$dbh, name=>'street', nocache=>0);
# Люди
my $Owners = $m->comp("lib.msn:userlist", dbh=>$dbh, nocache=>0);
# Столбы
my $Towers = $m->comp("lib.msn:listload", dbh=>$dbh, name=>'towers', nocache=>0);
# Типы счетчиков
my $Ctypes = $m->comp("lib.msn:listload", dbh=>$dbh, name=>'counter_type', nocache=>0);
# Текущие показания счетчиков
my $LastCounter = $m->comp("lib.msn:lastcounter", dbh=>$dbh, id=>0, nocache=>0);

my ($List, $Usr);
# Группы
$sth = $dbh->prepare("select * from mgroup");
$sth->execute();
while(my $r = $sth->fetchrow_hashref) {
	$List->{$r->{id}} = $r;
}
$sth->finish;

if($id) {
	$sth = $dbh->prepare("select * from counters where id=?");
	$sth->execute($id);
	while(my $r = $sth->fetchrow_hashref) {
		$Usr = $r;
	}
	$sth->finish;
}

if($ARGS{submit} && $auth->{gid} eq 1) {
	if($ARGS{delete} && $id) {	# удаление записи
#		$dbh->do("delete from counters where id=$id");
		$dbh->do("UPDATE counters SET active=-1 WHERE id=$id");
		undef $id;
		$OK++;
	} else {
		my $active = $ARGS{active}? 1:0;
		map { $ARGS{$_} =~ s/\D//g; $ARGS{$_} ||= 0 } ('addr','mgroup','sn','model','tower_id','year','street','owner');
		map { $ARGS{$_} = 0 if($ARGS{$_} > 2000000000) } ('addr','mgroup','sn','model','tower_id','year','street','owner');
		$ARGS{plimit} =~ s/\,/\./g;
		$ARGS{plimit} =~ s/[^0-9\.]//g;
		$ARGS{plimit} = 3.6	if(!$ARGS{plimit} or $ARGS{plimit} == 0 or $ARGS{plimit} > 10000);
		my ($mday,$mon,$year) = (localtime)[3,4,5];
		$ARGS{setdate} ||= sprintf("%4d-%02d-%02d",$year+1900,$mon+1,$mday);

		unless(%Err) {
			if($Usr) {	# Обновление
				my $chg = ($active ne $Usr->{active})? 1:0;
				map {$chg++ if($ARGS{$_} ne $Usr->{$_})} ('name','addr','mgroup','sn','model','setdate','memo','tower_id','year','street','house','owner','plimit');
				if($chg) {	# есть изменения
					my $upd = $dbh->prepare("update counters set name=?,addr=?,mgroup=?,sn=?,model=?,setdate=?,memo=?,active=?,tower_id=?,year=?,street=?,house=?,owner=?,modtime=now(),plimit=? where id=?");
					$upd->execute($ARGS{name},$ARGS{addr},$ARGS{mgroup},$ARGS{sn},$ARGS{model},$ARGS{setdate},$ARGS{memo},$active,$ARGS{tower_id},$ARGS{year},$ARGS{street},$ARGS{house},$ARGS{owner},$ARGS{plimit},$id);
				}
			} else {	# Новая запись

				my ($passwd1,$passwd2) = ('','');
				if($Ctypes->{$ARGS{model}}->{type} eq 'M230') { ($passwd1,$passwd2) = ('111111','222222'); }
				my $ins = $dbh->prepare("insert into counters (name,addr,mgroup,sn,model,setdate,memo,active,tower_id,year,street,house,owner,passwd,passwd2,modtime,plimit) values (?,?,?,?,?,?,?,?,?,?,?,?,?,\'$passwd1\',\'$passwd2\',now(),?)");
				$ins->execute($ARGS{name},$ARGS{addr},$ARGS{mgroup},$ARGS{sn},$ARGS{model},$ARGS{setdate},$ARGS{memo},$active,$ARGS{tower_id},$ARGS{year},$ARGS{street},$ARGS{house},$ARGS{owner},$ARGS{plimit});
			}
			undef $id;
			undef $ARGS{"add_new"};
			$OK++;
#			$m->clear_buffer;
#			# The next two lines are necessary to stop Apache from re-reading POSTed data.
#			$r->method('GET');
#			$r->headers_in->unset('Content-length');
#			$r->content_type('text/html');
#			$r->header_out('Location' => 'index.html');
#			$m->abort(301);
		}
	}
}

if(!$ARGS{"add_new"} && !$id && !$OK) {
	# Счетчики полный список
#	$sth = $dbh->prepare("select counters.id,counters.name,counters.addr,counters.mgroup,counters.passwd,counters.sn,counters.model,counters.setdate,counters.memo,counters.active,counters.modtime,counters.passwd2,counters.ktrans,counters.tower_id,counters.year,counters.street,counters.house,status.id as status_id,status.state,status.pstate,status.se1,status.se2,status.modtime as status_modtime from counters left outer join status on status.cid=counters.id");
#	$sth->execute();
#	while(my $r = $sth->fetchrow_hashref) {
#		push @{$List->{$r->{mgroup}}->{items}}, $r;
#	}
#	$sth->finish;

	my $L = $m->comp("lib.msn:cflistload", dbh=>$dbh, nocache=>1);
	foreach(keys %$L) { $List->{$_}->{items} = $L->{$_}->{items}; }

}
</%init>
%#<pre>
%#<%Dumper $auth%>
%#</pre>
%if($OK) {
<h3>Запись сохранена</h3>
<p><a href="index.html">Home</a></p>
%} elsif($id || $ARGS{"add_new"}) {
<form method="POST">
<input type="hidden" name="add_new" value="<%$ARGS{"add_new"}%>">
<p><a href="index.html">Отменить</a></p>
<table border="1">
<tr>
<td>Используется:</td>
<td><input type="checkbox" name="active" <% $ARGS{active} || (!$ARGS{submit} ? $Usr->{active} : "") ? "checked":""%> <% ($auth->{gid} >1) ? "disabled":"" %>>
%	if($id) {
<div align=right><small>modtime: <%$Usr->{modtime} =~ /(.+)\.\d+/%></small></div>
%	}
</td>
</tr>
<tr>
<td>Название:</td>
<td><input type="text" name="name" value="<%$ARGS{name} || (!$ARGS{submit} ? $Usr->{name} : "")%>" <% ($auth->{gid} >1) ? "disabled":"" %>></td>
</tr>
<tr>
<td>Сетевой адрес:</td>
<td><input type="text" name="addr" value="<%$ARGS{addr} || (!$ARGS{submit} ? $Usr->{addr} : "") %>" <% ($auth->{gid} >1) ? "disabled":"" %>></td>
</tr>
<tr>
<td>Группа:</td>
<td><select name="mgroup" <% ($auth->{gid} >1) ? "disabled":"" %>>
<option></option>
%	foreach my $gid (sort {$List->{$a}->{name} cmp $List->{$b}->{name}} keys %$List) {
<option value="<%$gid%>" <% ((!$ARGS{submit} ? $Usr->{mgroup} : $ARGS{mgroup}) eq $gid)? "selected":"" %>><%$List->{$gid}->{name}%></option>
%	}
</select></td>
</tr>
<tr>
<td>Серийный номер:</td>
<td><input type="text" name="sn" value="<%$ARGS{sn} || (!$ARGS{submit} ? $Usr->{sn} : "") %>" <% ($auth->{gid} >1) ? "disabled":"" %>></td>
</tr>
<tr>
<td>Год выпуска:</td>
<td><input type="text" name="year" value="<%$ARGS{year} || (!$ARGS{submit} ? $Usr->{year} : "")%>" <% ($auth->{gid} >1) ? "disabled":"" %>></td>
</tr>
<tr>
<td>Тип:</td>
<td><select name="model" <% ($auth->{gid} >1) ? "disabled":"" %>>
<option></option>
%	foreach my $cid (sort {$Ctypes->{$a}->{name} cmp $Ctypes->{$b}->{name}} keys %$Ctypes) {
<option value="<%$cid%>" <% ((!$ARGS{submit} ? $Usr->{model} : $ARGS{model}) eq $cid)? "selected":"" %>><%$Ctypes->{$cid}->{name}%></option>
%	}
</select></td>
</tr>
<tr>
<td>Проезд:</td>
<td><select name="street" <% ($auth->{gid} >1) ? "disabled":"" %>>
<option></option>
%	foreach my $sid (sort {$S->{$a}->{name} cmp $S->{$b}->{name}} keys %$S) {
<option value="<%$sid%>" <% ((!$ARGS{submit} ? $Usr->{street} : $ARGS{street}) eq $sid)? "selected":"" %>><%$S->{$sid}->{name}%></option>
%	}
</select></td>
</tr>
<tr>
<td>Участок:</td>
<td><input type="text" name="house" value="<%$ARGS{house} || (!$ARGS{submit} ? $Usr->{house} : "")%>" <% ($auth->{gid} >1) ? "disabled":"" %>></td>
</tr>
<tr>
<td>Владелец:</td>
<td>
<select name="owner" <% ($auth->{gid} >1) ? "disabled":"" %>>
<option></option>
%	foreach my $uid (sort {$Owners->{$a}->{lname} cmp $Owners->{$b}->{lname}} keys %$Owners) {
%		next	unless($Owners->{$uid}->{lname});
<option value="<%$uid%>" <% ((!$ARGS{submit} ? $Usr->{owner} : $ARGS{owner}) eq $uid)? "selected":"" %>><%$Owners->{$uid}->{name} || $Owners->{$uid}->{lname}%></option>
%	}
</select>
</td>
</tr>
<tr>
<td>Столб:</td>
<td><select name="tower_id" <% ($auth->{gid} >1) ? "disabled":"" %>>
<option></option>
%	foreach my $sid (sort {$Towers->{$a}->{name} <=> $Towers->{$b}->{name}} keys %$Towers) {
<option value="<%$sid%>" <% ((!$ARGS{submit} ? $Usr->{"tower_id"} : $ARGS{"tower_id"}) eq $sid)? "selected":"" %>><%$Towers->{$sid}->{name}%></option>
%	}
</select></td>
</tr>
<tr>
<td>Дата установки:</td>
<td><input type="text" name="setdate" value="<%$ARGS{setdate} || (!$ARGS{submit} ? $Usr->{setdate} : "")%>" <% ($auth->{gid} >1) ? "disabled":"" %>></td>
</tr>
<tr>
<td>Лимит мощности:</td>
<td><input type="text" name="plimit" value="<%$ARGS{plimit} || (!$ARGS{plimit} ? $Usr->{plimit} : "")%>" <% ($auth->{gid} >1) ? "disabled":"" %>></td>
</tr>
<tr>
<td>Примечания:</td>
<td><textarea name="memo" cols="30" rows="2" <% ($auth->{gid} >1) ? "disabled":"" %>><%$ARGS{memo} || (!$ARGS{submit} ? $Usr->{memo} : "")%></textarea></td>
</tr>

%#	modtime timestamp default now(),

%if($auth->{gid} eq 1) {
<tr>
<td></td>
<td><input type="submit" name="submit" value="Сохранить">&nbsp;<i>удалить</i><input type="checkbox" name="delete"></td>
</tr>
%}

</table>
%if($filter) {
<input type="HIDDEN" name="filter" value="<%$filter%>">
%}
%if($filter2) {
<input type="HIDDEN" name="filter2" value="<%$filter2%>">
%}
</form>
%} else {	# полный список
%	my ($sec,$min,$hour,$mday,$mon,$year) = (localtime)[0,1,2,3,4,5];

%if($auth->{gid} eq 1) {
<style type="text/css">
	#ping
		{
		width: 50%;
		position: fixed;
		// top: 0;
		left: 50%;
		//position: absolute;
		top: expression(
			document.getElementsByTagName( 'body' )[0].scrollTop + "px"
		);
	}
</style>
<iframe name="ping" id="ping" align="right" frameborder="0" width="50%" style:"position:fixed;">iframe не поддерживается</iframe>
%}

<div class="masthead">
	<ul class="nav nav-pills pull-left">
		<li class="active"><a href="/">Home</a></li>
		<li><a href="expense.html">Расходы</a></li>
%if($auth->{gid} < 3) {
		<li><a href="pays.html">Платежи</a></li>
%}
%if($auth->{gid} eq 1) {
		<li><a href="user.html">Персоны</a></li>
		<li><a href="auth.html">authors</a></li>
%}
	</ul>
%#	<h3 class="muted">GHPower</h3>
</div>
<hr>

<p><br></p>
<form name="filter" method="POST">
<select name="filter">
<option value="0">-- все группы --</option>
%foreach my $mgid (sort {$List->{$a}->{rank} <=> $List->{$b}->{rank}} keys %$List) { 
%	next unless $List->{$mgid}->{items};
<option value="<%$mgid%>" <% $filter && $mgid == $filter ? "selected":""%>><% $List->{$mgid}->{name}%></option>
%}
</select>
<select name="filter2">
<option value="0">-- все счетчики --</option>
<option value="1" <%$filter2 eq '1' ? "selected":""%>>-- активные --</option>
<option value="2" <%$filter2 eq '2' ? "selected":""%>>-- неактивные --</option>
</select>
<label class="checkbox">
<input type="checkbox" name="showdel" <%$showdel ? "checked":""%>>Показывать удаленные
</label>
<input class="btn" type="submit" name="sel" value="Выбрать">
</form>

<h2>Текущие показания счетчиков</h2>
<p><%sprintf("%4d-%02d-%02d %02d:%02d:%02d",$year+1900,$mon+1,$mday,$hour,$min,$sec)%></p>

%if($auth->{gid} eq 1) {
<p>gid: [<%$filter%>]</p>

<form method="POST">
<p><input class="btn" type="submit" name="add_new" value="Добавить счетчик">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</p>
</form>
%}

<table border="1" class="table-condensed">
%foreach my $mgid (sort {$List->{$a}->{rank} <=> $List->{$b}->{rank}} keys %$List) {
%	next if $filter &&  !($mgid == $filter);
%	next unless $List->{$mgid}->{items};
<tr>
<td><input type="checkbox" name="mgid_<%$mgid%>" <% ($ARGS{"mgid_".$mgid} || $List->{mgid}->{active}) ? "checked":""%> disabled></td>
<td><b><% $List->{$mgid}->{name}%></b></td>
<td colspan="9"><% $List->{$mgid}->{memo}%></td>
</tr>
%	my $i=1; my $total=0;
%	foreach my $item (sort { $S->{$a->{street}}->{name} cmp $S->{$b->{street}}->{name} || $a->{house} <=> $b->{house}} @{$List->{$mgid}->{items}}) {
%		if($filter2) {
%			next	if($filter2 eq '1' && $item->{active} ne '1');
%			next	if($filter2 eq '2' && $item->{active});
%		}
%		next	if($item->{active} < 0 && !$showdel);
<tr>
<td align="center"><%$i%>.</td>
<td align="right"><a href="?id=<%$item->{id}%>"><%$item->{addr} ? $item->{addr} : "---"%></a> (<%$item->{sn}%>)</td>
%	my $parcel;
%	if($item->{street}) {
%		$parcel = $item->{street};
%		$parcel = $S->{$item->{street}}->{name};
%		$parcel = substr($parcel, 0, 1);
%		$parcel .= '.-';
%	} $parcel .= $item->{house};
<td><% $parcel %></td>
<td><% $Owners->{$item->{owner}}->{name} || $Owners->{$item->{owner}}->{lname}%></td>
<td><%$Towers->{$item->{tower_id}}->{name}%></td>
%#<td align="right"><a href="energy.html?id=<%$item->{id}%><%$filter ? "&filter=$filter":""%>"><%$LastCounter->{$item->{id}}->{t1}%></a></td>
%#<td align="right"><a href="energy.html?id=<%$item->{id}%><%$filter ? "&filter=$filter":""%>"><%$LastCounter->{$item->{id}}->{t2}%></a></td>

<td align="right"><%$LastCounter->{$item->{id}}->{t1}%></td>
<td align="right"><%$LastCounter->{$item->{id}}->{t2}%></td>

%my $mark = ($LastCounter->{$item->{id}}->{lpower} > $item->{plimit}) ? "style=color:red;font-weight:bold":"";
<td align="right"><a href="energy.html?id=<%$item->{id}%><%$filter ? "&filter=$filter":""%>"><div <%$mark%>> <%$LastCounter->{$item->{id}}->{lpower} ? $LastCounter->{$item->{id}}->{lpower} : "_"%></div></a></td>
% my $lpow = $LastCounter->{$item->{id}}->{lpower}; $lpow =~ s/\,/\./;
% $total += $lpow;
<td><input type="checkbox" name="id_<%$item->{id}%>" <% ($ARGS{"id_".$item->{id}} || $item->{active}) ? "checked":""%> disabled></td>
<td>
%if($auth->{gid} eq 1) {
<a href="ping.html?id=<%$item->{id}%>" target="ping">ping</a>
%}
</td>
<td><img src="/images/<% defined $item->{state} ? ($item->{state} ? "critical.png":"recovery.png") : "warning.png" %>"></td>

</tr>
%	$i++;
%	}
% $total=~s/\./\,/;
<tr><td colspan=7 align=right>Сумма:</td><td align=right><b><%$total%></b></td><td colspan=3></td></tr>
%}
</table>

%}




<pre>
%#<% Dumper $Usr %>
%#<% Dumper %ARGS %>
</pre>


